package com.sa.module.uif.serviceImpl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import com.sa.commons.constant.HttpSessionKey;
import com.sa.commons.web.mvc.interceptor.HttpObject;
import com.sa.module.uif.dao.UsersDAO;
import com.sa.module.uif.pojo.Users;
import com.sa.module.uif.service.LoginRegistService;

import com.sa.commons.exception.DBErrorException;

public class LoginRegistServiceImpl implements LoginRegistService {

	@Autowired
	private UsersDAO usersDAO;
	
	public String login(String email, String password,
			Map<String, Object> model) throws Exception {
		Map<String, Object> equalsMap = new HashMap<String, Object>();
		equalsMap.put(UsersDAO.EMAIL, email);
		equalsMap.put(UsersDAO.PASSWORD, password);
		List<Users> list = usersDAO.findEntity(equalsMap, 0, 1);
		if (list.size() == 0) {
			return "用户名或密码输入错误!";
		}
		HttpObject.getHttpSession().setAttribute(HttpSessionKey.USER_KEY,
				list.get(0));
		return null;
	}

	public String reg(String email, String password, Map<String, Object> model) throws Exception {
		Map<String, Object> equalsMap = new HashMap<String, Object>();
		equalsMap.put(UsersDAO.EMAIL, email);
		long count = usersDAO.countEntity(equalsMap);
		if (count != 0) {
			return "已存在的邮箱地址!";
		}

		Users users = new Users();
		users.setEmail(email);
		users.setIsOfficial(0);
		users.setLeadNum(0);
		users.setHomePage("");
		users.setOpenTime(new Timestamp(System.currentTimeMillis()));
		users.setPassword(password);
		users.setPicture("");
		users.setStoreNum(0);
		users.setTagIds("");
		String[] str = email.split("@");
		users.setUserName(str[0]);

		Transaction tran = usersDAO.getSession().beginTransaction();
		try{
			usersDAO.save(users);
			tran.commit();
			usersDAO.getSession().flush();
		}catch(DBErrorException e){
			tran.rollback();
			throw e;
		}
		
		usersDAO.getSession().flush();
		usersDAO.getSession().clear();

		if (users.getId() == 0) {
			return "注册失败!";
		}
		HttpObject.getHttpSession().setAttribute(HttpSessionKey.USER_KEY,
				users);
		return null;
	}

	public String logout(Map<String, Object> model) throws Exception {
		HttpObject.getHttpSession().removeAttribute(HttpSessionKey.USER_KEY);
		return null;
	}

}
